from flask import Flask, jsonify, request
from datetime import datetime
import threading

from modbus_rtu_client import ModbusRTUClient
from public_fuction import get_device_params, get_device_data

SERVER_IP = 'localhost'
SERVER_PORT = 8204


class FlaskServer:
    def __init__(self, port=SERVER_PORT):
        self.port = port
        self.is_running = False
        self.app = Flask(__name__)
        self.server_thread = None
        self._setup_routes()

    def _setup_routes(self):
        @self.app.route('/api/time')
        def get_time():
            return jsonify({"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})

        @self.app.route('/api/data')
        def get_data():
            args = self._process_args()
            try:
                modbus_client = ModbusRTUClient(**args)
                data = get_device_data(modbus_client)
                modbus_client.close()
            except Exception as e:
                data = {'error': str(e)}
            return jsonify({"data": data})

        @self.app.route('/api/params', methods=['GET'])
        def get_params():
            args = self._process_args()
            try:
                modbus_client = ModbusRTUClient(**args)
                data = get_device_params(modbus_client)
                modbus_client.close()
            except Exception as e:
                data = {'error': str(e)}
            return jsonify({"data": data})

    @staticmethod
    def _process_args():
        args = {}
        for k, v in request.args.items():
            if str(v).isdigit():
                args[k] = int(v)
            else:
                args[k] = v
        return args

    def run(self):
        """在独立线程中启动Flask服务"""
        self.server_thread = threading.Thread(
            target=lambda: self.app.run(port=self.port, debug=False, use_reloader=False)
        )
        self.server_thread.daemon = True
        self.server_thread.start()
        self.is_running = True

    def stop(self):
        """停止服务（可选实现）"""
        # 需要额外库实现强制关闭，此处仅标记线程终止
        self.server_thread.join(timeout=1)
        self.is_running = False
